package com.ruoyi.web.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.H5User;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.mapper.UserMerchantMapper;
import com.ruoyi.web.mapper.UserOrderMapper;
import com.ruoyi.web.domain.UserMerchant;
import com.ruoyi.web.domain.UserOrder;
import com.ruoyi.web.service.IUserMerchantService;

/**
 * 商户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@Service
public class UserMerchantServiceImpl implements IUserMerchantService 
{
    @Autowired
    private UserMerchantMapper userMerchantMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;

    /**
     * 查询商户
     * 
     * @param id 商户主键
     * @return 商户
     */
    @Override
    public UserMerchant selectUserMerchantById(Long id)
    {
        return userMerchantMapper.selectUserMerchantById(id);
    }

    /**
     * 查询商户列表
     * 
     * @param userMerchant 商户
     * @return 商户
     */
    @Override
    public List<UserMerchant> selectUserMerchantList(UserMerchant userMerchant)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String client = SecurityUtils.getClientType();
        if(!client.equals("h5")){
            SysUser sysUser = loginUser.getUser();
            if(sysUser.getRoles().get(0).getRoleId() != 1){
                userMerchant.setCompanyId(Long.parseLong(sysUser.getBindUserId()));
            }
        }else{
            H5User h5User = loginUser.getH5User();
            if(h5User.getTop().equals(0L)){
                userMerchant.setCompanyId(h5User.getId());
            }else{
                userMerchant.setCompanyId(h5User.getTop());
            }
        }
        List<UserMerchant> merchants = userMerchantMapper.selectUserMerchantList(userMerchant);
        if(client.equals("h5")){
            Long[] ids = merchants.stream()
                .map(UserMerchant::getId)
                .toArray(Long[]::new);
            List<UserOrder> userOrders =  userOrderMapper.getCountByIds(ids);
            // 1. 统计每个 merchantId 的数量
            Map<Long, Long> countMap = userOrders.stream()
                .collect(Collectors.groupingBy(UserOrder::getMerchantId, Collectors.counting()));

            // 2. 给 merchants 赋值
            for (UserMerchant merchant : merchants) {
                Long count = countMap.getOrDefault(merchant.getId(), 0L);
                merchant.setSettlementOrder(count.intValue());
            }
        }
        return merchants;
    }

    /**
     * 新增商户
     * 
     * @param userMerchant 商户
     * @return 结果
     */
    @Override
    public int insertUserMerchant(UserMerchant userMerchant)
    {
        userMerchant.setCreateTime(DateUtils.getNowDate());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String client = SecurityUtils.getClientType();
        if(!client.equals("h5")){
            SysUser sysUser = loginUser.getUser();
            if(sysUser.getRoles().get(0).getRoleId() != 1){
                userMerchant.setCompanyId(Long.parseLong(sysUser.getBindUserId()));
            }
        }else{
            H5User h5User = loginUser.getH5User();
            if(h5User.getTop().equals(0L)){
                userMerchant.setCompanyId(h5User.getId());
            }else{
                userMerchant.setCompanyId(h5User.getTop());
            }
            userMerchant.setUserid(h5User.getId());
        }
        return userMerchantMapper.insertUserMerchant(userMerchant);
    }

    /**
     * 修改商户
     * 
     * @param userMerchant 商户
     * @return 结果
     */
    @Override
    public int updateUserMerchant(UserMerchant userMerchant)
    {
        userMerchant.setUpdateTime(DateUtils.getNowDate());
        return userMerchantMapper.updateUserMerchant(userMerchant);
    }

    /**
     * 批量删除商户
     * 
     * @param ids 需要删除的商户主键
     * @return 结果
     */
    @Override
    public int deleteUserMerchantByIds(Long[] ids)
    {
        // 删除商户之前需先确认是否还有未结算的订单
        List<UserOrder> userOrders = userOrderMapper.getCountByIds(ids);
        if(userOrders.size()>0){
            throw new UserException("merchant.delete.has.order",null);
        }

        return userMerchantMapper.deleteUserMerchantByIds(ids);
    }

    /**
     * 删除商户信息
     * 
     * @param id 商户主键
     * @return 结果
     */
    @Override
    public int deleteUserMerchantById(Long id)
    {
        return userMerchantMapper.deleteUserMerchantById(id);
    }
}
